import React from 'react'
import axios from 'axios';
import './index.scss'
import { useState, useEffect } from 'react'

import { Space, Button, Tag } from 'antd'
import type { ColumnsType } from 'antd/es/table';

import SearchForm from '@/components/Form/SearchForm';
import TableList from '@/components/TableList/TableList';
import EditDialog from './components/editDialog/index';

import { searchList, buttonList, status } from "./option"
import moment from 'moment';

import DayPlanApi from '@/pages/Plan/api/dayPlan';
import download from '@/utils/download';
import confirmDialog from '@/utils/confirmDialog';

const dayPlanApi = new DayPlanApi;

interface DataType {
    key: React.Key;
    name: string,
    createTime: string
}

export default function DayPlan() {
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            render: (text, record, index) => `${index + 1}`,
        },
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '计划名',
            dataIndex: 'planName',
            key: 'planName',
        },
        {
            title: '计划分类',
            dataIndex: 'planType',
            key: 'planType',
            render: (_: any, record: any) => (
                <div>{record.planType.label}</div>
            ),
        },


        {
            title: '开始时间',
            dataIndex: 'startTime',
            key: 'startTime',
        },
        {
            title: '结束时间',
            dataIndex: 'endTime',
            key: 'endTime',
        },
        {
            title: '状态',
            key: 'achieveStatus',
            render: (_: any, { achieveStatus }: any) => {
                let color;
                switch (achieveStatus) {
                    case 0:
                        color = 'green';
                        break;
                    case 1:
                        color = 'red';
                        break;
                    case 2:
                        color = 'orange';
                        break;
                    case 3:
                        color = 'cyan';
                        break;
                }
                return (
                    <Tag color={color} key={achieveStatus}>
                        {status[achieveStatus]}
                    </Tag>
                )
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
        },
        {
            title: '用户手机号',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: any) => (
                <Space size="middle">
                    <a onClick={() => modifyPlan(record)}>编辑</a>
                    <a onClick={() => deletePlan(record.id)} style={{ color: 'red' }}>删除</a>
                </Space>
            ),
        },
    ];
    // 列表数据
    const [data, setData] = useState<any>();
    const [search, setSearch] = useState(searchList)
    const [typeList, setTypeList] = useState();
    const [dialogData, setDialogData] = useState({
        dialogVisible: false,
        title: '',
        data: {}
    })
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0

    })

    //获取分类信息
    const getType = () => {
        //对象数组是引用方式 ,对于react来说它的值都是地址(涉及到tree diff)，因为没有被重新赋值(地址没有改变)，所以 react 会认为仍然是之前的元素(element)，则不更新视图
        //解决方法：浅拷贝方式获取对象并修改再赋值。
        let searchL = [...search]
        axios.get('/api/plan/type').then((res: any) => {
            let typeList = res.data.data.map((item: any) => {
                return Object.assign({}, { 'value': item.id, 'label': item.name })
            })
            setTypeList(typeList)
            searchL.map((item: any) => {
                if (item.label === '计划分类') {
                    item.options = typeList
                }
            })
            setSearch(searchL)
        })
    }

    // 获取列表数据
    const getData = (value?: any) => {
        if (value && value.startTime) {
            value.startTime = value.startTime.format('YYYY-MM-DD 00:00:00')
        }

        if (value && value.endTime) {
            value.endTime = value.endTime.format('YYYY-MM-DD 23:59:59')
        }

        if (value && value.createTime) {
            value.createTime = value.createTime.format('YYYY-MM-DD 23:59:59')
        }

        let params = {
            data: value,
            current: pagination.current,
            pageSize: pagination.pageSize
        }

        dayPlanApi.planList(params).then((res) => {
            if (res) {
                setData(res.data)
                let page = pagination
                page.total = res.totalCount
                setPagination(page)
            }
        })
    }
    // 点击筛选
    const onQuery = (values: any) => {
        console.log(values);
        getData(values)
    }
    // 重置
    const onReset = () => {
        getData()
    }

    // 导出
    const exportData = () => {
        dayPlanApi.exportData().then((res) => {
            download(res)
        })
    }

    // 新增
    const onAdd = () => {
        setDialogData({
            dialogVisible: true,
            title: '新增',
            data: {}
        })
    }

    // 编辑弹框
    const modifyPlan = (value: any) => {
        setDialogData({
            dialogVisible: true,
            title: '编辑',
            data: {
                ...value,
                planType: value.planType,
                timeLine: [moment(value.startTime, 'YYYY-MM-DD'), moment(value.endTime, 'YYYY-MM-DD')],
                achieveStatus: value.achieveStatus + ''
            }
        })
    }

    // 删除弹框
    const deletePlan = (id: string) => {
        confirmDialog('确认删除?', () => {
            dayPlanApi.deletePlan(id).then((res) => {
                getData()
            })
        })
    }

    //监听翻页数据变化
    const pageChange = (current: number, pageSize: number) => {
        let page = pagination
        page.current = current
        page.pageSize = pageSize
        setPagination(page)
        getData()
    }
    const currentChange = (current: number) => {
        let page = pagination
        page.current = current
        setPagination(page)
        getData()
    }
    // 新增弹框-点击确定
    const submit = (value: any) => {
        getData()
        setDialogData({
            dialogVisible: false,
            title: '',
            data: {}
        })
    }



    // 副作用
    useEffect(() => {
        // 获取分类信息
        getType()
        // 获取列表信息
        getData()
    }, []);

    return (
        <div>
            {/* 搜素栏 */}
            <SearchForm searchList={search} buttonList={buttonList} onQuery={onQuery} onReset={onReset} onExport={exportData}>
                <Button type="primary" htmlType="button" onClick={onAdd} style={{ marginLeft: 20 }}>
                    新增
                </Button>
            </SearchForm>

            {/* <input type="file" id="datafile"></input> */}

            {/* 数据列表 */}
            <TableList columns={columns} initData={data} pagination={pagination} pageChange={pageChange} currentChange={currentChange}>
            </TableList>

            {/* 新增编辑弹框 */}
            <EditDialog title={dialogData.title} planTypes={typeList} initialValues={dialogData.data} dialogVisible={dialogData.dialogVisible} onSubmit={submit}></EditDialog>
        </div >
    )
}
